package io.rong.app.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yunshipei.adapter.MessageHistoryAdapter;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.MessageHistoryModel;
import com.yunshipei.model.SortModel;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.ClearEditText;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import io.rong.app.model.GroupCreateInfo;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.model.Event;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;

public class SearchGroupMessageActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private TextView goBack;
    private ClearEditText searchEdit;
    private ListView listView;
    private DatabaseUtil databaseUtil = null;
    private GroupCreateInfo groupInfo;
    private List<MessageHistoryModel> messageList = null;
    private MessageHistoryAdapter mAdapter = null;
    private MessageHistoryModel messageHistoryModel = null;
    private String keyStr;
    private RelativeLayout titlebar;
    private TextView search_no_results_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(BaseUtil.getCurrentTheme());
        setContentView(R.layout.activity_search_group_message);
        initView();
        initData();
    }

    private void initView() {
        goBack = (TextView) findViewById(R.id.go_back);
        searchEdit = (ClearEditText) findViewById(R.id.search_edit);
        searchEdit.setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.close), null);
        listView = (ListView) findViewById(R.id.message_history);
        goBack.setOnClickListener(this);
        listView.setOnItemClickListener(this);
        mAdapter = new MessageHistoryAdapter(this);
        listView.setAdapter(mAdapter);
        titlebar = (RelativeLayout) findViewById(R.id.title_bar_container);
        titlebar.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        search_no_results_tv=(TextView)findViewById(R.id.search_no_results);
    }

    private void initData() {
        if (getIntent() != null) {
            groupInfo = (GroupCreateInfo) getIntent().getBundleExtra("groupInfo").getSerializable("groupInfo");
        }
        databaseUtil = new DatabaseUtil();
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyStr = s.toString();
                if (mAdapter != null)
                    mAdapter.setKey(keyStr);
                SearchTask searchTask = new SearchTask();
                searchTask.execute(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_back:
                InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive() && this.getCurrentFocus() != null) {
                    if (this.getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                this.finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MessageHistoryModel messageHistoryModel = (MessageHistoryModel) parent.getAdapter().getItem(position);
        if (!TextUtils.isEmpty(messageHistoryModel.getTargetId())) {
            startConversation(this, messageHistoryModel.getMessage().getConversationType(), messageHistoryModel.getTargetId(), messageHistoryModel.getMessage().getMessageId(), null);
        }
    }

    public void startConversation(Context context, Conversation.ConversationType conversationType, String targetId, int messageId, String title) {

        if (context == null || TextUtils.isEmpty(targetId) || conversationType == null)
            throw new IllegalArgumentException();

        if (RongContext.getInstance() == null)
            throw new ExceptionInInitializerError("RongCloud SDK not init");

        Uri uri = Uri.parse("rong://" + context.getApplicationInfo().processName).buildUpon()
                .appendPath("conversation").appendPath(conversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", targetId).appendQueryParameter("title", title)
                .appendQueryParameter("messageId", String.valueOf(messageId)).build();

        context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }

    private class SearchTask extends AsyncTask<String, Void, List<Message>> {
        @Override
        protected List<Message> doInBackground(String... params) {
            String searchKey = params[0];
            List<Message> list = databaseUtil.getImMsg(groupInfo.getId(), searchKey);
            return list;
        }

        @Override
        protected void onPostExecute(List<Message> list) {

            String content;
            Iterator<Message> iterator = list.iterator();
            Message message = null;
            messageList = new ArrayList<>();
            while (iterator.hasNext()) {
                messageHistoryModel = new MessageHistoryModel();
                message = iterator.next();
                if (message.getContent() instanceof TextMessage && ((TextMessage) message.getContent()).getContent().indexOf(keyStr) >= 0) {
                    messageHistoryModel.setMessage(message);
                    messageHistoryModel.setAvator(groupInfo.getPortraitUri());
                    messageHistoryModel.setTargetId(groupInfo.getId());
                    messageHistoryModel.setTitle(groupInfo.getName());
                    messageList.add(messageHistoryModel);
                }
            }

            if (messageList.size()==0)
            {
                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
                spannableStringBuilder.append("没有搜到包含");
                SpannableStringBuilder colorFilterStr = new SpannableStringBuilder(keyStr);
                colorFilterStr.setSpan(new ForegroundColorSpan(Color.parseColor("#ff0000")), 0, keyStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                spannableStringBuilder.append(colorFilterStr);
                spannableStringBuilder.append("聊天信息");
                search_no_results_tv.setEllipsize(TextUtils.TruncateAt.valueOf("MIDDLE"));
                search_no_results_tv.setLines(1);
                search_no_results_tv.setText(spannableStringBuilder);

                if (search_no_results_tv.getVisibility()==View.GONE){
                    search_no_results_tv.setVisibility(View.VISIBLE);
                }
            }

            if (messageList.size()>0||TextUtils.isEmpty(keyStr))
            {
                if (search_no_results_tv.getVisibility()==View.VISIBLE) {
                    search_no_results_tv.setVisibility(View.GONE);
                }
            }
            mAdapter.clear();
            mAdapter.addDatas(messageList);
            mAdapter.notifyDataSetChanged();

        }
    }
}
